import { createReducer } from 'reduxsauce'
import { REHYDRATE } from 'redux-persist/es/constants'
import {
  GET_MY_COUPON_LIST
} from '@ACTIONS/coupon'

const INITIAL_STATE = {
  myCouponList: [],
  loadingMyCouponList: true,
  initLoadingMyCouponList: true,
  canLoadMyCouponList: true,
  error: null,
}

const rehydrate = (state, { payload }) => {
  if (payload && payload.consultation) {
    return { ...INITIAL_STATE, ...payload.consultation }
  }
  return { ...state }
}

export default createReducer(INITIAL_STATE, {
  [REHYDRATE]: rehydrate,

  [GET_MY_COUPON_LIST.REQUEST]: (state, { payload: { skip } = {} }) => {
    const { myCouponList, initLoadingMyCouponList } = state
    const isInitSkip = skip === 0
    return ({
      myCouponList: isInitSkip ? [] : myCouponList,
      initLoadingMyCouponList: isInitSkip ? true : initLoadingMyCouponList,
      loadingMyCouponList: true
    })
  },
  [GET_MY_COUPON_LIST.SUCCESS]: (state, { data, canLoadMore }) => ({
    myCouponList: data,
    loadingMyCouponList: false,
    initLoadingMyCouponList: false,
    canLoadMyCouponList: canLoadMore
  }),
  [GET_MY_COUPON_LIST.FAILURE]: (state, { error }) => ({
    ...state,
    error
  })
})
